# -*- encoding: utf-8 -*-
"""
-文件        : db.py
-说明        : 区块链数据库接口
-作者        : tlj
"""

import pickle
import os


class DB:
    def __init__(self, db_file):
        self._db_file = db_file

        try:
            with open(self._db_file, 'rb') as f:
                self.kv = pickle.load(f)

        except FileNotFoundError:
            print("新建数据文件", self._db_file)
            self.kv ={}

    def commit(self):
        """保存"""

        with open(self._db_file, 'wb') as f:
            pickle.dump(self.kv, f)

    def get(self, key):
        return self.kv[key]

    def put(self, key, value):
        self.kv[key] = value

    def delete(self, key):
        if key in self.kv:
            del self.kv[key]

    def reset(self):
        self.kv = {}

    def get_file(self):
        return self._db_file

